package com.shoulder.mybatis.utils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class BigInUtils {

    public static <E> List<E> selectBatchByIds(BaseMapper<E> baseMapper, List<? extends Serializable> ids) {
        int batchSize = 1000; // 每批1000个ID
        List<E> result = new ArrayList<>();

        for (int i = 0; i < ids.size(); i += batchSize) {
            List<? extends Serializable> batchIds = ids.subList(i, Math.min(i + batchSize, ids.size()));
            List<E> batchUsers = baseMapper.selectBatchIds(batchIds);
            result.addAll(batchUsers);
        }
        return result;
    }


    public static <E, T> List<E> selectList(BaseMapper<E> baseMapper, List<? extends Serializable> ids, LambdaQueryWrapper<E> queryWrapper
            , SFunction<E, T> func) {
        List<E> result = new ArrayList<>();

        int batchSize = 1000; // 每批1000个ID
        for (int i = 0; i < ids.size(); i += batchSize) {
            List<? extends Serializable> batchIds = ids.subList(i, Math.min(i + batchSize, ids.size()));
            LambdaQueryWrapper<E> batchWrapper = new LambdaQueryWrapper<>();
            batchWrapper.setEntity(queryWrapper.getEntity());
            batchWrapper.setEntityClass(queryWrapper.getEntityClass());

            if (queryWrapper.getExpression().getNormal().size() > 0) {
                queryWrapper.getExpression().getNormal().forEach(condition -> batchWrapper.getExpression().getNormal().add(condition));
            }

            batchWrapper.in(func, batchIds);
            List<E> batchUsers = baseMapper.selectList(batchWrapper);

            result.addAll(batchUsers);
        }
        return result;
    }
}
